//
//  AppDelegate.m
//  hotkeyapp
//
//  Created by flynn on 2025/2/26.
//

#import "AppDelegate.h"

#import <Cocoa/Cocoa.h>
#import <CoreGraphics/CoreGraphics.h>

@interface AppDelegate()
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    CGEventMask eventMask = CGEventMaskBit(kCGEventKeyUp);
    CFMachPortRef eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, eventMask, myCGEventCallback, NULL);
    
    if (!eventTap) {
        NSLog(@"Failed to create event tap.");
        exit(1);
    }
    
    CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
    
    CGEventTapEnable(eventTap, true);
}

static CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
    if (type != kCGEventKeyUp) return event;
    
    CGKeyCode keyCode = (CGKeyCode)CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode);
    CGEventFlags flags = CGEventGetFlags(event);
    
    if ((flags & kCGEventFlagMaskAlternate) && keyCode == 8 /* 'c' key */) {
        NSLog(@"Alt+C up %d",time(NULL));
        // 在这里处理你的逻辑
        [AppDelegate postCommandCEvent];
    }
    
    return event;
}
+ (void)postCommandCEvent {
    // 创建 Cmd 键按下事件
    CGEventRef commandDown = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)55, true); // 55 is the keycode for the left Command key
    // 创建 Cmd 键释放事件
    CGEventRef commandUp = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)55, false);
    // 创建 'c' 键按下事件
    CGEventRef cDown = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)8, true); // 8 is the keycode for 'c'
    // 创建 'c' 键释放事件
    CGEventRef cUp = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)8, false);

    // 设置 Cmd 键标志位
    CGEventSetFlags(cDown, kCGEventFlagMaskCommand);
    CGEventSetFlags(cUp, kCGEventFlagMaskCommand);

    // 发送事件
    CGEventPost(kCGAnnotatedSessionEventTap, commandDown);
    CGEventPost(kCGAnnotatedSessionEventTap, cDown);
    CGEventPost(kCGAnnotatedSessionEventTap, cUp);
    CGEventPost(kCGAnnotatedSessionEventTap, commandUp);

    // 释放事件对象
    CFRelease(commandDown);
    CFRelease(commandUp);
    CFRelease(cDown);
    CFRelease(cUp);
}
@end
